package com.item.web.sys_menu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.item.web.sys_menu.entity.MakeMenuTree;
import com.item.web.sys_menu.entity.SysMenu;
import com.item.web.sys_menu.mapper.SysMenuMapper;
import com.item.web.sys_menu.service.SysMenuService;
import com.item.web.sys_role_menu.entity.RoleMenu;
import com.item.web.sys_role_menu.service.RoleMenuService;
import com.item.web.sys_user_role.entity.SysUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private RoleMenuService roleMenuService;

    @Override
    @Transactional
    public void deleteMenu(Long menuId) {
        // 删除指定 menuId 的用户记录数
        int i = this.baseMapper.deleteById(menuId);
        if(i > 0){
            // 删除角色菜单关联记录
            QueryWrapper<RoleMenu> query = new QueryWrapper<>();
            query.lambda().eq(RoleMenu::getMenuId, menuId);
            roleMenuService.remove(query);
        }
    }

    @Override
    public List<SysMenu> getParent() {
        String[] type = {"0","1"};
        List<String> strings = Arrays.asList(type);
        QueryWrapper<SysMenu> query = new QueryWrapper<>();
        query.lambda().in(SysMenu::getType,strings);
        List<SysMenu> menuList = this.baseMapper.selectList(query);
        //无数据则组装默认的一个菜单
        SysMenu menu = new SysMenu();
        menu.setTitle("顶级菜单");
        menu.setParentId(-1L);
        menu.setMenuId(0L);
        menuList.add(menu);
        //组装上级菜单树
        List<SysMenu> tree = MakeMenuTree.makeTree(menuList, -1L);
        return tree;
    }

    @Override
    public List<SysMenu> getMenuByUserId(Long userId) {
        return this.baseMapper.getMenuByUserId(userId);
    }

    @Override
    public List<SysMenu> getMenuByRoleId(Long roleId) {
        return this.baseMapper.getMenuByRoleId(roleId);
    }
}
